package com.sdp.th.netty.bizc;

import java.math.BigDecimal;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.sdp.core.bizc.utils.ApplicationContextUtils;
import com.sdp.right.db.sys_config.service.ISysConfigService;
import com.sdp.right.entity.SysConfig;
import com.sdp.th.cache.ThCleanCache;
import com.sdp.th.cache.caches.EqStateCache;
import com.sdp.th.db.th_eq_alarm_log.service.IThEqAlarmLogService;
import com.sdp.th.db.th_eq_alarm_trend_log.service.IThEqAlarmTrendLogService;
import com.sdp.th.db.th_eq_message.service.IThEqMessageService;
import com.sdp.th.db.th_eq_power.service.IThEqPowerService;
import com.sdp.th.db.th_eq_state.service.IThEqStateService;
import com.sdp.th.db.th_eq_state_log.service.IThEqStateLogService;
import com.sdp.th.entity.ThEqMessage;
import com.sdp.th.entity.ThEqPower;
import com.sdp.th.entity.ThEqState;
import com.sdp.th.entity.ThEqStateLog;
import com.sdp.th.utils.ThConstants;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class MessageDataBusinessImpl implements BusinessService{

	@Override
	public void execute(Object obj) {
		
		ThEqState thEqState = (ThEqState) obj;
		
		//原始报文
		ThEqMessage thEqMessage = new ThEqMessage();
		thEqMessage.setCreateTime(thEqState.getReportTime());
		BeanUtils.copyProperties(thEqState, thEqMessage);
		ApplicationContextUtils.getBean(IThEqMessageService.class).save(thEqMessage);
		log.info("**************数据库添加《原始报文》业务完成");
		
		//实时状态日志
		ThEqStateLog thEqStateLog = new ThEqStateLog();
		BeanUtils.copyProperties(thEqState, thEqStateLog);
		thEqStateLog.setCreateTime(thEqState.getReportTime());
		ApplicationContextUtils.getBean(IThEqStateLogService.class).insertEqStateLog(thEqStateLog);
		log.info("**************数据库添加《实时状态日志》业务完成");
		
		//处理报警
		boolean isAlarm = ApplicationContextUtils.getBean(IThEqAlarmLogService.class).verifyTHAlarm(thEqState);
		thEqState.setAlarmState(isAlarm?ThConstants.是.getCode():ThConstants.否.getCode());
		log.info("**************《实时报警》业务完成");
		
		//处理趋势报警
		ApplicationContextUtils.getBean(IThEqAlarmTrendLogService.class).verifyTrendAlarm(thEqState);
		log.info("**************《趋势报警》业务完成");
		
		//更新实时信息
		ThEqState dbThEqState = ApplicationContextUtils.getBean(IThEqStateService.class).updateState(thEqState);
		log.info("**************更新《实时信息》业务完成");
		
		//更新缓存
		if(dbThEqState==null) {
			//删除缓存
			ApplicationContextUtils.getBean(ThCleanCache.class).cleanEqStateCache(thEqState.getDeviceNo());
		}else {
			ApplicationContextUtils.getBean(EqStateCache.class).updateStateCache(dbThEqState);

		}
		log.info("**************《更新缓存》业务完成");
		
	}

	@Override
	public BusinessEnum getBusinessType() {
		return BusinessEnum.报文处理业务;
	}

}
